package com.lql.stack;

import java.util.Arrays;

/**
 * 使用数组模拟栈
 */
public class ArrayStackDemo {

    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(3);
        arrayStack.push(1);
        arrayStack.push(2);
        arrayStack.push(3);
        System.out.println("_______________");
        arrayStack.showStack();
    }
}



class ArrayStack {
    private int maxSize;//栈的最大容量
    private int[] arrayStack;// 模拟栈结构
    private int top = -1;//表示栈顶指针变量

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.arrayStack = new int[maxSize];
    }

    public int getMaxSize() {
        return maxSize;
    }

    public void setMaxSize(int maxSize) {
        this.maxSize = maxSize;
    }

    public int[] getArrayStack() {
        return arrayStack;
    }

    public void setArrayStack(int[] arrayStack) {
        this.arrayStack = arrayStack;
    }

    public int getTop() {
        return top;
    }

    public void setTop(int top) {
        this.top = top;
    }

    @Override
    public String toString() {
        return "ArrayStack{" +
                "maxSize=" + maxSize +
                ", arrayStack=" + Arrays.toString(arrayStack) +
                ", top=" + top +
                '}';
    }

    /**
     * 栈满
     *
     * @return
     */
    public boolean isFull() {
        return top == maxSize - 1;
    }

    /**
     * 栈空
     *
     * @return
     */
    public boolean isEmpty() {
        return top == -1;
    }

    /**
     * 入栈
     */
    public void push(int num) {
        if (isFull()) {
            throw new RuntimeException("栈已满，入栈失败");
        }
        arrayStack[++top] = num;
    }

    /**
     * 出栈
     *
     * @return
     */
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空，出栈失败");
        }
        return arrayStack[top--];
    }

    /**
     * 显示栈内元素
     */
    public void showStack() {
        if (isEmpty()) {
            System.out.println("栈为空");
        }

        for (int i = top; i >= 0; i--) {
            System.out.println(arrayStack[i]);
        }
    }
}